function previewCode(id) {
    commonUtil.openNewWindow(rooturl + "/admin/previewCode/" + id);
}

function openEdit(id) {
    layer.open({
        type: 2
        , title: '详细页'
        , content: rooturl + "/admin/genTable/" + id//页面路径
        , maxmin: true
        , area: [(document.body.clientWidth - 10) + "px", (document.body.clientHeight - 10) + "px"]
        , btn: ['确定', '取消']
        , yes: function (index, layero) {
            //点击确认触发 iframe 内容中的按钮提交
            var submit = layero.find('iframe').contents().find("#submitBtnTable");
            submit.click();
            listTableFresh();
        }
    });
}

function listTableFresh() {
    $('.mySubmitBtn').click();
}

function getChirld(id, html) {
    var mychild = [{
        title: '选择'
        , action: "select"
        , id: id
        , html: html
    }, {
        title: '编辑'
        , action: "edit"
        , id: id
        , html: html
    }, {
        title: '删除'
        , action: "del"
        , id: id
        , html: html
    }];
    return mychild;
}

function initDataSources() {
    var datas = new Array;
    var options = $("#datasourceId").find("option");
    var selectSid = $("#datasourceId").val();
    for (var i = 0; i < options.length; i++) {
        var sid = $(options[i]).attr("value");
        if (selectSid == sid) {
            $("#dataSourceList").html("数据源：" + $(options[i]).html());
        }

        var item = {
            title: $(options[i]).html()
            , id: sid
            , child: getChirld(sid, $(options[i]).html())
        }
        datas.push(item);
    }

//多级下拉菜单
    dropdown.render({
        elem: '#dataSourceList'
        , data: datas
        , click: function (item) {
            if ("edit" == item.action) {
                commonUtil.openNewWindow(rooturl + "/admin/editSource/" + item.id);
            } else if ("del" == item.action) {

                layer.confirm('真的删除行么', function (index) {
                    var datax = {id: item.id};
                    commonUtil.sendRequest("POST", datax, "/datasource/del");
                    layer.close(index);
                });
            } else if ("select" == item.action) {
                $("#dataSourceList").html("数据源：" + item.html);
                $("#datasourceId").val(item.id);
                listTableFresh();
            }
        }
    });

    $("#datasourceView").hide();
}

var isInit = 0;

function sendRequst(typex, datax, urlx) {

    var tishi = layer.load(1, {
        shadeClose: false,
        title: '加载中..',
        shade: [0.8, '#fff'] //0.1透明度的白色背景
    });

    $.ajax({
        url: urlx,
        type: typex,
        data: datax,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.code != "0") {
                layer.msg("操作失败" + JSON.stringify(data));
                layer.close(tishi);
                return;
            }
            layer.msg("操作成功");

            if(isUpLast!=$("#isUp").val()){
                table.reload('testReload', {
                    toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                    , data: data.data
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }

            table.reload('testReload', {
                toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                , data: data.data
            });

            initDataSources();
            isInit++;
            layer.close(tishi);
            isUpLast=$("#isUp").val();
        }
    });

}

function sendRequestImport(typex, datax, urlx) {
    $.ajax({
        url: urlx,
        type: typex,
        data: datax,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            console.log(data);
            listTableFresh();
        },
        error: function (data) {
            console.log('error');
        }
    });
}

//搜索按钮
var isUpLast;
$('.mySubmitBtn').on('click', function () {
    var mysearch = {
        "id": 0,
        "isUp": $("#isUp").val(),
        "needFresh": $("#needFresh").val(),
        "sid": $("#datasourceId").val(),
        "tableComment": $("#tableComment").val(),
        "tableName": $("#tableName").val()
    };

    sendRequst("POST", JSON.stringify(mysearch), rooturl + "/gentable/table");

});


//加载模块
layui.use(function () { //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
    //得到各种内置组件
    listTableFresh();
    table.render({
        elem: '#demo'
        , id: 'testReload'
        // ,url: 'http://localhost/gentable/table'
        // , where: { sid: 1}             //如果无需传递额外参数，可不加该参数
        , method: 'post'          //如果无需自定义HTTP类型，可不加该参数
        , contentType: 'application/json'
        , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
        , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            title: '提示'
            , layEvent: 'LAYTABLE_TIPS'
            , icon: 'layui-icon-tips'
        }]
        , height: 420
        , title: '用户表'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , totalRow: true //开启合计行
        , limit: 30
        , height: 'full-200'
        , cellMinWidth: 200
        , cols: [[ //表头
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', title: 'id'}
            , {field: 'tableName', title: 'tableName'}
            , {field: 'comment', title: 'comment'}
            , {field: 'gid', width: 180, title: '模板组', templet: '#gidTemplate', unresize: true}
            // , {field: 'gid', title: 'gid'}
            , {fixed: 'right', width: 350, align: 'center', toolbar: '#barDemo'}
        ]],
        done: function (res, curr, count) {
            layui.each($('.selectFieldTypeClass'), function (index, item) {
                var elem = $(item);
                elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
            });
            form.render();
        },
        initSort: {
            field: 'tableName' //排序字段，对应 cols 设定的各字段名
            , type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        }
    });


    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'addSource':
                var data = checkStatus.data;
                commonUtil.openNewWindow(rooturl + "/admin/addSource");
                break;
            case 'codeGenList':
                var datax = new Array();
                var data = checkStatus.data;
                if (data.length > 0) {
                    for (var item of checkStatus.data) {
                        datax.push(item.id); //  datax = {ids: ["15", "16"] };  console.log(datax)
                    }
                    datax = {ids: datax}
                    var url = rooturl + '/gentable/codeGenTableByIds';
                    $.download(url, datax);
                } else {
                    layer.msg("没有选择的目标");
                }
                break;
            case 'codeGenListo':
                var datax = new Array();
                var data = checkStatus.data;
                if (data.length > 0) {
                    for (var item of checkStatus.data) {
                        datax.push(item.id); //  datax = {ids: ["15", "16"] };  console.log(datax)
                    }
                    datax = {ids: datax}
                    var url = rooturl + '/gentable/codeGenByOnlies';
                    $.download(url, datax);
                } else {
                    layer.msg("没有选择的目标");
                }
                break;
            //自定义头工具栏右侧图标 - 提示
            case 'LAYTABLE_TIPS':
                layer.alert('自定义图标按钮');
                break;
        }
    });

    //监听行单击事件（双击事件为：rowDouble） row 单击
    table.on('rowDouble(test)', function (obj) {
        var data = obj.data;
        if(data.id==null){
            layer.msg("未导入,无法预览");
            return;
        }

        commonUtil.openNewWindow(rooturl + "/admin/previewCodeByOnline/" + data.id + "/0");
        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            , layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent === 'detail') {
            if(data.id == null){
                layer.msg("请导入");
                layer.close(index);
                return;
            }
            if (data.id != null) {
                openEdit(data.id);
            }
        } else if (layEvent === 'getCode') {
            if (data.id != null) {
                location.href = rooturl + "/gentable/codeGen/" + data.id;
            }
        } else if (layEvent === 'getCodeo') {
            if (data.id != null) {
                location.href = rooturl + "/gentable/codeGenByOnlie/" + data.id;
            }
        } else if (layEvent === 'previewCodeByOnline') {
            if (data.id != null) {
                commonUtil.openNewWindow(rooturl + "/admin/previewCode/" + data.id);
                // commonUtil.openNewWindow(rooturl + "/admin/previewCodeByOnline/" + data.id + "/0");
            }
        } else if (layEvent === 'more') {
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                , show: true //外部事件触发即显示
                , data: [{
                    title: '删除'
                    , id: 'del'
                }, {
                    title: '导入'
                    , id: 'import'
                }]
                , click: function (menudata) {
                    if (menudata.id === 'del') {
                        layer.confirm('真的删除行么', function (index) {
                            if(data.id == null){
                                layer.msg("请导入");
                                layer.close(index);
                                return;
                            }
                            if (data.id != null) {
                                commonUtil.sendRequest("DELETE", "", "/gentable/" + data.id);
                                obj.del(); //删除对应行（tr）的DOM结构
                                layer.close(index);
                            }
                        });
                    } else if (menudata.id === 'import') {
                        layer.confirm('导入表结构', function (index) {
                            var sid = $("#datasourceId").val();
                            var requestData = {
                                "comment": data.comment,
                                "sid": sid,
                                "tableName": data.tableName
                            };
                            sendRequestImport("POST", JSON.stringify(requestData), rooturl + "/gentable/tableImport");
                            layer.close(index);
                        });
                    }
                }
                , align: 'right' //右对齐弹出（v2.6.8 新增）
                , style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        }
    });
});